from PyQt5.QtWidgets import QApplication
import win32gui
import base64
import time
import sys
import io
from PIL import ImageQt

import requests

def screenshot(title):
    print("正在截屏……")
    hwnd = win32gui.FindWindow(None, title)
    app = QApplication(sys.argv)
    screen = QApplication.primaryScreen()
    qimage = screen.grabWindow(hwnd).toImage()
    qimage.save("3.jpg")
    return ImageQt.fromqimage(qimage)

def imgToBase64(image):
    imgByteArr = io.BytesIO()
    image.save(imgByteArr, format('JPEG'))
    imgByteArr = imgByteArr.getvalue()
    data = base64.b64encode(imgByteArr)
    return data

def baiduOCR(data):
    d = {}
    d['image'] = data
    print("文字转换ing……")
    res = {}
    r = requests.post('https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=24.4fe317c618b58057fc32aea0ad8773c2.2592000.1596359086.282335-20823601', data=d)
    res = r.json()

    while res.has_key('words_result') == False:
        r1 = requests.post(
            'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=24.4fe317c618b58057fc32aea0ad8773c2.2592000.1596359086.282335-20823601',
            data=d)
        res = r1.json()
        time.sleep(1000)
    i = 0
    wordsList = []
    for words in res['words_result']:
        print("    " + str(i) + ": " + words['words'])
        wordsList.append(words['words'])
        i += 1
    n = input("输入问题行, 输入+结束\n")

    list = []
    while n != "+":
        list.append(int(n))
        n = input()
    strings = ""
    for i in list:
        strings += wordsList[i]
    return strings

def inquire(question):
    print("问题：" + question)
    headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit 537.36 (KHTML, like Gecko) Chrome"}
    url = 'http://qs.nnarea.cn/OnlineCourseBot/topic?q=' + question
    print("查找答案ing")
    print("\n")
    r = requests.post(url, headers= headers)
    res = r.json()
    print("答案: " + res['answer'])
    print("\n")



if __name__ == '__main__':
    title = input("输入投屏软件标题\n")
    while True:
        print("键入任意以开始答案查找, 键入q结束")
        s = input()
        if s == 'q':
            break
        image = screenshot(title)
        data = imgToBase64(image)
        question = baiduOCR(data)
        inquire(question)
        # 示例 修改了代码